package com.java复习.jdbc.sqlHelper;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class SqlHelper<E> {
    private static Connection connection;

    static{
        if(connection==null){
            try{
                //1、加载数据库驱动程序
                Class.forName("com.mysql.cj.jdbc.Driver");

                //2、通过驱DriverManager获取数据库连接
                String url = "jdbc:mysql://localhost:3306/demo3?user=root&password=root" +
                        "&useSSL=false&serverTimezone=UTC&useUnicode=true" +
                        "&characterEncoding=utf8";
                connection = DriverManager.getConnection(url);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    //增、删 、修对数据库的操作封装
    public static boolean update(String sql,Object[] paras){
        boolean b = false;
        try{
            PreparedStatement ps = connection.prepareStatement(sql);
            if(paras!=null) {
                //注入参数
                for (int i = 0; i < paras.length; i++) {
                    ps.setObject(i + 1, paras[i]);
                }
            }
            //4、执行
            int total = ps.executeUpdate();
            if(total>0){
                b = true;
            }
            //5、关闭资源
            ps.close();

        }catch (Exception e){
            e.printStackTrace();
        }
        return b;
    }


    // 查
    public static <E>  List<E> query(String sql,Class<E> clazz,Object[] paras){
        List<E> list = new ArrayList<E>();
        try {
            //1、获得ps工具类
            PreparedStatement ps = connection.prepareStatement(sql);
            //2、参数注入
            if(paras!=null) {
                //注入参数
                for (int i = 0; i < paras.length; i++) {
                    ps.setObject(i + 1, paras[i]);
                }
            }
            //3、执行查询
            ResultSet rs = ps.executeQuery();

            //4、获取传入类型中的所有字段
            Field[] fields = clazz.getDeclaredFields();

            fields[0].getName();  //获得字段名称


            //4、获取结果
            while(rs.next()){
                E e = clazz.newInstance();
                for(int i=0;i< fields.length;i++){
                    Field field = fields[i];
                    Object field_val = rs.getObject(field.getName());
                    field.setAccessible(true);
                    field.set(e,field_val);
                }
                list.add(e);
            }
            rs.close();
            ps.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        return list;
    }


    public static void closeConn(){
        if(connection!=null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}
